package com.example.tool.task.networkTool;

/**
 * @Author lz
 * @Date 2022/2/23 13:48
 */

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 查询天气DEMO
 */
public class URLCon {

    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    //实现http和https两种get
    //还未将两种合并到一个方法


    public static void main(String[] args) throws IOException {


        URLCon demo = new URLCon();
//        demo.sendHttps("https://ditu.amap.com/service/regeo?longitude=121.04925573429551&latitude=31.315590522490712");
       // demo.sendHttps("https://p.3.cn/prices/mgets?skuIds=10032517142933&type=1");
//        demo.sendHttp("http://wthrcdn.etouch.cn/weather_mini?city=北京市","UTF-8");
    demo.sendHttp("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2021/14/03/21/140321104.html","UTF-8");
//                     http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2021/14/03/21/140321104.html
    }

    private  void sendHttp(String uri,String charsetName){
        try {
//            String urlStr = "https://ditu.amap.com/service/regeo?longitude=121.04925573429551&latitude=31.315590522490712"; //101221502 可在这里查询：http://blog.csdn.net/zgyulongfei/article/details/7956118，也可以在<中国天气>官网上点击查看具体城镇，地址栏就有这个id
            URL url = new URL(uri);
            HttpURLConnection  conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            System.out.println("连接中...");
            if(conn.getResponseCode()== 200){
                InputStream inputStream = null;
                ByteArrayOutputStream outputStream = null;
                try {
                    System.out.println("进来了...");
                    inputStream = conn.getInputStream();
                    outputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0 ;
                    while((len = inputStream.read(buffer)) != -1){
                        outputStream.write(buffer, 0, len);
                        outputStream.flush();
                    }
                    byte[] bytes = outputStream.toByteArray();
//                    System.out.println("数据："+outputStream.toByteArray());
                    System.out.println("====================");
                    String charset = new String(bytes, charsetName);
                    System.out.println("data:"+charset);
//                    for (int i = 0; i <bytes.length ; i++) {
//                        System.out.print((char)bytes[i]);
//                    }
                } catch (IOException e) {
                    System.out.println("数据读取出错...");
                    e.printStackTrace();
                } finally{
                    outputStream.close();
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            System.out.println("连接出错...");
            e.printStackTrace();
        }
    }

    private void sendHttps(String uri) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        //绕过HTTPS相关证书关键代码-开始
        conn.setSSLSocketFactory(ssf);
        //绕过HTTPS相关证书关键代码-结束
        conn.setConnectTimeout(5000);
        System.out.println("连接中...");
        if(conn.getResponseCode()== 200){
            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                System.out.println("进来了...");
                System.out.println(System.getProperty("sun.jnu.encoding"));
                System.out.println(Charset.defaultCharset().name());
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0 ;
                while((len = inputStream.read(buffer)) != -1){
                    outputStream.write(buffer, 0, len);
                    outputStream.flush();
                }
                byte[] bytes = outputStream.toByteArray();
                System.out.println("数据："+outputStream.toByteArray());
                System.out.println("====================");
                String gbk = new String(bytes, "UTF-8");
                System.out.println("GBK:"+gbk);

            } catch (IOException e) {
                System.out.println("数据读取出错...");
                e.printStackTrace();
            } finally{
                outputStream.close();
                inputStream.close();
            }

    }


    }



}